#include "ThreadService.h"
#include "foreach.h"
#include <cstdio>
#include <boost/shared_ptr.hpp>

std::map<std::string,ThreadServicePtr> ThreadService::ServiceMap;
ThreadService::ThreadService()
{
	mContinue = true;
	mWaitQueue = false;
    Start();
}
void ThreadService::DestroyAll()
{
    ServiceMap.clear();
}
void ThreadService::Destroy(const std::string& serviceName)
{
    ServiceMap.erase(serviceName);
}
ThreadService::~ThreadService()
{
    mMutex.lock();
    mContinue = false;
    mCallBackList.clear();
    std::cout<<"Destruindo...\n";
    mMutex.unlock();
}
ThreadServicePtr ThreadService::NewService(const std::string& serviceName)
{
    if(ServiceMap.count(serviceName)==0)
        return ServiceMap[serviceName] = ThreadServicePtr(new ThreadService());
    else
        return ServiceMap[serviceName];
}
ThreadServicePtr ThreadService::GetService(const std::string& serviceName)
{
    if (serviceName == "_MainService_")
        if (ServiceMap.count(serviceName)==0)
            ServiceMap[serviceName] = ThreadServicePtr(new ThreadService());

    return ServiceMap[serviceName];
}
void ThreadService::Add(const FunctionCallback& c, const std::string& serviceName)
{
    ServiceMap[serviceName]->Add(c);
};
void ThreadService::Add(const FunctionCallback& c)
{
    mMutex.lock();
    mWaitQueue = true;
    mCallBackList.push_back(c);
    mMutex.unlock();
};
void ThreadService::Start()
{
    mContinue = true;
    boost::thread trd(boost::bind( &ThreadService::Service, this ));
}
void ThreadService::Stop()
{
    mContinue = false;
}
void ThreadService::Service()
{
    while (mContinue)
    {
        mMutex.lock();
        FunctionCallback callback;
        //std::deque<FunctionCallback>::iterator it = mCallBackList.begin();
        //for(;it!=mCallBackList.end();++it)
        foreach(callback,mCallBackList)
        {
            callback();
        }

        mCallBackList.clear();
        mWaitQueue = false;
        mMutex.unlock();
        Sleep(1);
    }

}
void ThreadService::Join()
{
    mMutex.lock();
    while (mWaitQueue==true)
    {
        mMutex.unlock();
        mMutex.lock();
    }
    mMutex.unlock();
}

